<template>
  <div class="activity-management">
    <h2>活动管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item label="社团">
          <el-select v-model="queryParams.clubId" placeholder="请选择社团" clearable
                    filterable >
            <el-option 
              v-for="club in clubOptions" 
              :key="club.id" 
              :label="club.name"
              :value="club.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动标题">
          <el-input v-model="queryParams.title" placeholder="请输入活动标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="活动地点">
          <el-input v-model="queryParams.location" placeholder="请输入活动地点" clearable></el-input>
        </el-form-item>
        <!-- <el-form-item label="活动时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          >
          </el-date-picker>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd" v-if="isAdmin || isClubLeader">添加活动</el-button>
    </div>
    
    <!-- 活动表格 -->
    <el-table v-loading="loading" :data="activityList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column label="社团名称" width="150">
        <template #default="scope">
          {{ scope.row.club ? scope.row.club.name : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="活动标题" width="200"></el-table-column>
      <el-table-column prop="location" label="活动地点" width="150"></el-table-column>
      <el-table-column prop="schedule" label="活动时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.schedule) }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="活动描述" show-overflow-tooltip></el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <!-- 只有管理员和社团负责人可以编辑 -->
          <el-button 
            v-if="isAdmin || (isClubLeader && isManagedClub(scope.row.clubId))"
            link 
            type="primary" 
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            link 
            type="danger" 
            @click="handleDelete(scope.row)" 
            v-if="isAdmin || (isClubLeader && isManagedClub(scope.row.clubId))">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getActivityList, deleteActivity } from '@/api/activity'
import { getClubList } from '@/api/club'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const activityList = ref([])
const total = ref(0)
const clubOptions = ref([])
const dateRange = ref([])

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  clubId: null,
  title: '',
  location: '',
  startTime: null,
  endTime: null
})

// 检查当前用户是否管理指定社团
const isManagedClub = (clubId) => {
  if (!clubId || !userInfo.value || !isClubLeader.value) return false
  
  const managedClubs = clubOptions.value.filter(club => club.leaderId === userInfo.value.id)
  return managedClubs.some(club => club.id === clubId)
}

// 监听日期范围变化
watch(dateRange, (newValue) => {
  if (newValue && newValue.length === 2) {
    queryParams.startTime = newValue[0]
    queryParams.endTime = newValue[1]
  } else {
    queryParams.startTime = null
    queryParams.endTime = null
  }
})

// 获取活动列表
const getList = async () => {
  loading.value = true
  try {
    // // 如果是社团负责人，只能查看自己管理的社团
    // if (isClubLeader.value && !isAdmin.value) {
    //   // 根据登录用户信息查询其管理的社团
    //   const userClubs = clubOptions.value.filter(club => club.leaderId === userInfo.value.id)
    //   if (userClubs.length > 0 && !queryParams.clubId) {
    //     // 如果用户没有选择特定社团，默认查询所有管理的社团的活动
    //     // 这里不需要设置 clubId，后端会根据用户角色进行过滤
    //   } 
    //   // else if (queryParams.clubId && !userClubs.some(club => club.id === queryParams.clubId)) {
    //   //   ElMessage.error('您无权查看此社团的活动')
    //   //   loading.value = false
    //   //   return
    //   // }
    // }
    
    const res = await getActivityList(queryParams)
    if (res.data && res.code === 200) {
      activityList.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表出错:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

// 加载社团列表
const loadClubs = async () => {
  try {
    let params = { pageSize: 1000 }
    
    // // 如果是社团负责人且不是管理员，只能看到自己管理的社团
    // if (isClubLeader.value && !isAdmin.value) {
    //   params.leaderId = userInfo.value.id
    // }
    
    const res = await getClubList(params)
    if (res.data && res.code === 200) {
      clubOptions.value = res.data.list
    } else {
      ElMessage.error(res.message || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表出错:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置
const handleReset = () => {
  queryParams.clubId = null
  queryParams.title = ''
  queryParams.location = ''
  dateRange.value = []
  queryParams.startTime = null
  queryParams.endTime = null
  queryParams.page = 1
  getList()
}

// 添加活动
const handleAdd = () => {
  router.push('/activities/add')
}

// 编辑活动
const handleEdit = (row) => {
  router.push(`/activities/edit/${row.id}`)
}

// 删除活动
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除活动 "${row.title}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteActivity(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除活动出错:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadClubs()
  getList()
})
</script>

<style scoped>
.activity-management {
  padding: 20px;
}

.search-form {
  background-color: #f5f7fa;
  padding: 18px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 